/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useMemo, useState } from 'react';
import type { ConnectState } from '@/models/connect';
import { connect } from 'umi';
import { Form, Input, Button, Modal, Statistic, Col, Row, message } from 'antd';
import type { AccountInfo, InnAccountInfoBrand } from '../types/InnAccountInfo';
import { InnAccountInfoCoulmns } from './utils';
import { getSmsCode, closeInnAccount } from '@/services/customerSearch';
import CommonTable from './_common/CommonTable';
import CommonResetButton from './_common/CommonResetButton';
const FormItem = Form.Item;
const { Countdown } = Statistic;

interface InnAccountInfoType {
  screenSize?: boolean;
  dispatch: any;
  accountInfo: AccountInfo;
  brandList: InnAccountInfoBrand[];
  tableLoading: boolean;
}
interface FormValuesType {
  phone?: string;
  psw?: string;
}

interface ModalType {
  onClose: any;
  visible: boolean;
  screenSize?: boolean;
  account: string;
}

const CancelModal = (props: ModalType) => {
  const defaultphone = '13041660021';
  const { onClose, visible, screenSize, account } = props;
  const [form] = Form.useForm();
  const [countdownStatus, setCountdownStatus] = useState<boolean>(false);
  const [formvalue, setFormvalue] = useState<FormValuesType>({
    phone: defaultphone,
  });

  const onFinish = async (values: FormValuesType) => {
    const { code, msg } = await closeInnAccount({ ...values, phone: account });
    if (code == 0) {
      message.success('操作成功');
      setCountdownStatus(false);
      form.resetFields();
      onClose('refresh');
    } else {
      message.error(msg);
    }
  };
  const getVerificCode = async () => {
    const { code, msg } = await getSmsCode({ phone: account });
    if (code == 0) {
      message.success('获取验证码成功');
      setCountdownStatus(true);
    } else {
      message.error(msg);
    }
  };
  const onValuesChange = (values: FormValuesType) => {
    setFormvalue({
      ...formvalue,
      ...values,
    });
  };
  return (
    <Modal
      visible={visible}
      onCancel={onClose}
      destroyOnClose
      footer={null}
      width={screenSize ? 350 : 500}
      title='确认注销'
      centered
    >
      <Form
        labelCol={{ span: 6 }}
        form={form}
        onFinish={onFinish}
        layout={'horizontal'}
        style={{ marginBottom: 20 }}
        onValuesChange={onValuesChange}
      >
        <FormItem
          label={'验证码'}
          name='code'
          rules={[{ required: true, message: '请输入验证码' }]}
        >
          <Row align='middle'>
            <Col span={14}>
              <Input allowClear style={{ width: '100% ' }} placeholder={'请输入验证码'} />
            </Col>
            <Col span={6} offset={1}>
              <Button disabled={countdownStatus} onClick={getVerificCode} type='primary'>
                {countdownStatus ? (
                  <Countdown
                    value={Date.now() + 1000 * 60}
                    format='ss'
                    onFinish={() => setCountdownStatus(false)}
                    suffix='后重新获取'
                    valueStyle={{ fontSize: '12px', color: '#666' }}
                  />
                ) : (
                  '获取验证码'
                )}
              </Button>
            </Col>
          </Row>
        </FormItem>

        <FormItem>
          <Row justify='center'>
            <Button type='primary' htmlType='submit' loading={false}>
              注销
            </Button>
          </Row>
        </FormItem>
      </Form>
    </Modal>
  );
};

const InnAccountInfo = (props: InnAccountInfoType) => {
  const { dispatch, screenSize, accountInfo, brandList = [], tableLoading } = props;
  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(false);

  const onModalClose = (isFresh: string) => {
    setVisible(false);
    if (isFresh === 'refresh') {
      form.submit();
    }
  };

  const accountInfoCoulmnsOperate = useMemo(
    () => ({
      title: '操作',
      dataIndex: 'operate',
      align: 'center',
      render: () =>
        accountInfo.cm_id ? (
          <Button type='primary' size='small' ghost onClick={() => setVisible(true)}>
            注销
          </Button>
        ) : (
          ''
        ),
    }),
    [accountInfo.cm_id],
  );

  const onFinish = (values: FormValuesType) => {
    dispatch({
      type: 'customerSearch/innAccountInfo',
      payload: {
        ...values,
      },
    });
  };

  const onReset = () => {
    form.resetFields();
    dispatch({
      type: 'customerSearch/save',
      payload: {
        innAccountInfoData: {},
      },
    });
  };

  return (
    <>
      <Form
        form={form}
        onFinish={onFinish}
        layout={screenSize ? 'vertical' : 'inline'}
        style={{ marginBottom: 20 }}
      >
        <FormItem
          label={'驿站账号'}
          name='phone'
          rules={[{ required: true, message: '请输入手机号' }]}
        >
          <Input allowClear style={{ width: 250 }} placeholder={'请输入手机号'} />
        </FormItem>

        <FormItem>
          <Button type='primary' htmlType='submit' loading={false}>
            查询
          </Button>
          <CommonResetButton onReset={onReset} />
        </FormItem>
      </Form>

      <CommonTable
        title='账号信息'
        columns={[
          ...InnAccountInfoCoulmns.accountInfo,
          accountInfo.cm_id ? accountInfoCoulmnsOperate : {},
        ]}
        datasource={accountInfo.cm_id ? [{ ...accountInfo, id: '1' }] : [{ id: '1' }]}
        loading={tableLoading}
      />
      <CommonTable
        title='开通品牌'
        columns={InnAccountInfoCoulmns.brandList}
        datasource={brandList}
        loading={tableLoading}
      />
      <CancelModal
        account={accountInfo.account}
        onClose={onModalClose}
        visible={visible}
        screenSize={screenSize}
      />
    </>
  );
};

export default connect(({ customerSearch, loading }: ConnectState) => ({
  accountInfo: customerSearch.innAccountInfoData?.account_info || {},
  brandList: customerSearch.innAccountInfoData?.brand || [{ id: '1' }],
  innAccountInfoData: customerSearch.innAccountInfoData,
  tableLoading: loading.effects['customerSearch/innAccountInfo'] || false,
}))(React.memo(InnAccountInfo));
